package com.gdit.zax.servletjsp;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.gdit.zax.Constant;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBPushMessage;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.Repost;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.webUtil;

public class SendPush extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//变量准备
		int type = TextUtil.String2int(request.getParameter("type"), 0);
		String data = request.getParameter("data");
		String content = request.getParameter("content");
		String token = webUtil.getCookie(request, "LoginCookie");
		
		//数据库，权限检测
		Connection conn = DBUtil.getConnection();
		if (conn == null) {
			Repost.dberror(request, response);
			return;
		}
		
		DAOFactory dao = new DAOFactory(conn, request, response);
		UserDao udao = dao.getUserDao();
		UserInfo info = udao.getInfo(Constant.LOGINTYPE_WEB, token);
		if (info==null) {
			Repost.nologin(response);
			return;
		}
		
		if (info.getUlevel()<Constant.ULEVEL_admin) {
			Repost.message("你没有权限操作!", request, response);
			return;
		}
		
		//开始处理
		int page = 1;
		List<UserInfo> list = null;
		int sum = 0;
		int sum_success=0;
		while((list = udao.listUser(page, 100)).size() != 0) {
			page++;
			for (UserInfo userInfo : list) {
				JSONObject jo = new JSONObject();
				jo.put("type", type);
				jo.put("data", data);
				jo.put("content", content);
				sum++;
				if (DBPushMessage.sendMessage(userInfo.getDbuserid(), jo.toJSONString())) {
					sum_success++;
				}
			}
		}
		
		Repost.message("推送成功!共推送" + sum + "个,成功:" + sum_success + "个!", request, response);
		
	}

}
